package com.itheima.reggie.controller;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.encoders.UTF8;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;


/**
 * @Author Pan Rundong
 * @Date 2023-02-05 9:23
 * @Desc 支付宝支付功能
 */
@RestController
@Slf4j
@RequestMapping( "/pay")
public class PayController {
    /**
     * 返回Url
     */
    @Value("${reggie.alipay.returnUrl}")
    private String returnUrl;

    @Autowired
    private OrdersService ordersService;

    /**
     * 支付
     * @Author: Pan Rundong
     * @Date: 2023-02-05 9:26
     * @Greet2u:  （O｀ 3′O）~~♡
     * @param id
     * @return com.itheima.reggie.common.R<java.lang.String>
     */
    @GetMapping("/confirm")
    public Object pay(Long id) throws Exception {
        //根据订单id获取订单
        Orders orders = ordersService.getById(id);
        String orderName = "order: " + id + ", Consignee: " + orders.getConsignee();


        //调用sdk，发起支付
        AlipayTradePagePayResponse response = Factory.Payment
                //选择网页支付平台
                .Page()
                //调用支付方法，设置订单名称、我们自己系统中的订单号、金额、回调页面
                .pay(orderName, id.toString(), orders.getAmount().toString(), returnUrl);


//        lipay_sdk=alipay-easysdk-java-2.0.0&amp;app_id=2021000122613937&amp;biz_content={&quot;out_trade_no&quot;:&quot;1622067065055653889&quot;,&quot;total_amount&quot;:&quot;5.00&quot;,&quot;subject&quot;:&quot;??:&quot;,&quot;product_code&quot;:&quot;FAST_INSTANT_TRADE_PAY&quot;}&amp;charset=UTF-8&amp;format=json&amp;method=alipay.trade.page.pay&amp;notify_url=http://5tvm8p.natappfree.cc/pay/fallback&amp;return_url=http://5tvm8p.natappfree.cc/return.html&amp;sign_type=RSA2&amp;timestamp=2023-02-05 10:58:19&amp;version=1.0
        //这里的response.body，就是一个可以直接加载的html片段，
        // 这里为了简单我直接返回这个片段，前端直接
        return response.body;
    }

    /**
     * 支付宝回调
     * @Author: Pan Rundong
     * @Date: 2023-02-05 14:06
     * @Greet2u:  （O｀ 3′O）~~♡
     * @param request
     * @return void
     */
    @PostMapping(value = "/fallback")
    public void fallback (HttpServletRequest request) {
        Map map = request.getParameterMap();
        //获取订单号
        String[] number = (String[]) map.get("out_trade_no");
        String id = number[0];
        log.info("订单" + id + "进入了回调");
        //根据Id获取对应订单
        Orders orders = ordersService.getById(id);

        //设置订单状态为2
        orders.setStatus(2);
        Long userId = orders.getUserId();
        log.info("userId = {}", userId);

        //更新订单信息
        ordersService.updateById(orders);
    }
}
